﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Crawler_v1.ui;

namespace Crawler_v1.spider
{
    class Spider
    {
        public int workerNum = 2;

        public int curNum = 0;

        private Queue queue;//url队列

        private MainForm form;

        private List<ContentPraser> cps = new List<ContentPraser>();

        private enum SpiderState { running, pause };

        private SpiderState state = SpiderState.pause;

        public Spider(MainForm form)
        {
            this.form = form;
            //url队列
            queue = new Queue(form);
            queue.init();
        }

        public void start()
        {
            form.printLog("spider 开始");
            state = SpiderState.running;

            for (int i = 0; i < workerNum; i++)
            {
                ContentPraser cp = new ContentPraser(form, queue);
                //cps.Add(cp);

                cp.startWorker(new Action<ContentPraser>(onNextStart));

                //ContentPraser cp = new ContentPraser(form);
                //Thread t2 = new Thread(new ParameterizedThreadStart(run));
                //t2.Start(cp);
            }

        }

        public void pause()
        {
            state = SpiderState.pause;
            form.printLog("spider 暂停，等待正在运行的进程结束");
        }


        public void onNextStart(ContentPraser cp)
        {

            form.printLog(cp.getCurUrl() + "解析完成");

            if (state == SpiderState.running)
            {
                cp.startWorker(new Action<ContentPraser>(onNextStart));
            }

        }

        /*
        public void run(object data)
        {
            ContentPraser cp = data as ContentPraser;
            Console.WriteLine("带参数的线程函数 run");
            while (!queue.isEnded())
            {

                if (!queue.IsEmpty())
                {
                    string url = queue.getOneUrl();
                    //解析
                    cp.parse(url, new Action(() =>
                    {

                    }));
                }
                Thread.Sleep(3000);
            }

        }
        */
    }
}
